package net.bwie.zg6.function;

import java.util.ArrayList;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;


/**
 * 自定义函数（UDTF）将字符串 'hello,world,hive' 按照逗号分割，输出每个单词
 * @author xuanyu
 * @date 2025/6/23
 */
public class ExplodeWordUDTF extends GenericUDTF{

	/**
	 * 1初始化工作，比如在处理数据之前准备事情：判断传递参数值是否异常
	 */
	@Override
	public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
		/*
				explode_split(word_str, ',')
				|
				'hello,hive,spark,flink'   -> [hello、hive、spark、flink]  4个元素
				'hello,hive'   -> [hello、hive]  2个元素
		 */
		// 1定义输出结果名称
		ArrayList<String> fieldNames = new ArrayList<String>();
		fieldNames.add("word");
		// 2定义输出结果类型
		ArrayList<ObjectInspector> fieldOIs = new ArrayList<ObjectInspector>();
		fieldOIs.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
		// 2返回
		return ObjectInspectorFactory.getStandardStructObjectInspector(fieldNames, fieldOIs);
	}

	/**
	 * 2处理每条数据，相当于UDF函数中evaluate方法
	 */
	@Override
	public void process(Object[] args) throws HiveException {
		// 1.获取参数值
		String wordStr = String.valueOf(args[0]);
		String speratorStr = String.valueOf(args[1]);
		// 2.分割字符串
		String[] split = wordStr.split(speratorStr);
		// 3. 输出
		for (String word : split) {
			forward(new String[]{word});
		}
	}

	/**
	 * 3收尾工作：数据处理完以后清理操作，比如关闭IO流或者连接Connection
	 */
	@Override
	public void close() throws HiveException {
	}

}


/*
 -- 创建函数
DROP FUNCTION explode_split ;
CREATE FUNCTION explode_split AS 'net.bwie.zg6.function.ExplodeWordUDTF'
    USING JAR 'hdfs://node101:8020/user/hive/jars/hive-udf.jar';

-- 测试函数
WITH tmp1 AS (
    SELECT 'hello,world,hive' AS word_str
)
SELECT
    word
FROM tmp1
    LATERAL VIEW explode_split(word_str, ',') tmp AS word
 */
